package com.yyysj.system.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yyysj.common.core.domain.TableDataInfo;
import com.yyysj.common.core.enums.ResultCode;
import com.yyysj.common.security.exception.ServiceException;
import com.yyysj.system.domain.dto.UserDTO;
import com.yyysj.system.domain.dto.UserQueryDTO;
import com.yyysj.system.domain.po.User;
import com.yyysj.system.domain.vo.UserVO;
import com.yyysj.system.manager.UserCacheManager;
import com.yyysj.system.mapper.UserMapper;
import com.yyysj.system.service.IUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
@RequiredArgsConstructor
public class UserServiceImpl implements IUserService {

    private final UserMapper userMapper;
    private final UserCacheManager userCacheManager;

    @Override
    public TableDataInfo list(UserQueryDTO userQueryDTO) {
        PageHelper.startPage(userQueryDTO.getPageNum(), userQueryDTO.getPageSize());
        List<UserVO> userVOList = userMapper.selectUserList(userQueryDTO);
        Page<UserVO> page = (Page<UserVO>) userVOList;
        if (page == null || page.getTotal() <= 0) {
            return TableDataInfo.empty();
        }
        PageInfo<UserVO> pageInfo = new PageInfo<>(page);
        return TableDataInfo.success(page.getResult(), pageInfo.getTotal());
    }

    @Override
    public int updateStatus(UserDTO userDTO) {
        User user = userMapper.selectById(userDTO.getUserId());
        if (user == null) {
            throw new ServiceException(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        user.setStatus(userDTO.getStatus());

        userCacheManager.updateStatus(user.getUserId(), userDTO.getStatus());
        return userMapper.updateById(user);
    }
}
